package com.geekstudy;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

@WebServlet(urlPatterns = "/demoJNDI", asyncSupported = false)
public class DemoJNDIServlet extends HttpServlet {

    @Override
    public void doGet(HttpServletRequest httpRequest, HttpServletResponse httpResponse) {

        try {

            httpResponse.setCharacterEncoding("UTF-8");
            httpResponse.setHeader("content-type","text/html;charset=UTF-8");

            outMessage(httpResponse, "演示JNDI 开始 </br>");

            Context context = new InitialContext();
            DataSource dataSource = (DataSource)context.lookup("java:comp/env/jdbc/mysqlGeekStudy");
            Connection connection = dataSource.getConnection();

            String catalog = connection.getCatalog();
            String url = connection.getMetaData().getURL();
            String username = connection.getMetaData().getUserName();
            String driverName = connection.getMetaData().getDriverName();
            String driverVersion = connection.getMetaData().getDriverVersion();
            //Properties properties = connection.getClientInfo();
            //properties.getProperty("user");
            String connectMessage = "catalog=" + catalog + " </br>url=" + url
                    + " </br>username=" + username + " </br>driverName=" + driverName
                    + " </br>driverVersion=" + driverVersion + " </br>";
            outMessage(httpResponse, connectMessage);

            String name = httpRequest.getParameter("name");
            if(name != null && !name.isEmpty()) {
                Statement statement = connection.createStatement();
                SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
                String id = simpleFormat.format(new Date());
                boolean insertResult = statement.execute("insert into geek_demo(id, name, type) values ('" + id + "', '" + name + "', 'demo')");
                outMessage(httpResponse, "</br>保存结果: " + insertResult);
                statement.close();
            }

            PreparedStatement preparedStatement = connection.prepareStatement("select count(*) as num from geek_demo");
            ResultSet resultSet = preparedStatement.executeQuery();
            for(;resultSet.next();) {
                int num = resultSet.getInt("num");
                outMessage(httpResponse, "</br> 数据表geek_demo记录数: " + num);
            }
            resultSet.close();
            preparedStatement.close();
            connection.close();

            outMessage(httpResponse, "</br>演示JNDI 2021 完成 </br>");

        } catch(Exception e) {
            e.printStackTrace();
            outMessage(httpResponse, e.getMessage());
        }

    }


    private void outMessage(HttpServletResponse httpResponse, String message) {
        try {
            httpResponse.getOutputStream().write(message.getBytes("UTF-8"));
        }  catch(IOException e) {
            System.out.println(e);
        }

    }

}
